//
//  MicroDataStoreHelper.swift
//  MicroAppStore
//
//  Created by 徐涛 on 2020/7/14.
//  Copyright © 2020 徐涛. All rights reserved.
//

import UIKit
import TinyUI
import TinyDataBase

class MicroDataStoreHelper: NSObject {
    var cachePath:String = "microAppStoreCache.json"   //存data json 文件
    var filePath:String = ""
    var currentStoreDataArr:NSMutableArray = NSMutableArray.init()
    var coverNewDataArr:NSMutableArray = NSMutableArray.init()
    var mallAppArr:NSMutableArray = NSMutableArray.init();//一个用于过滤的数组(后面最好是由服务端做!)记录了micAppType 0() 1(微服务应用) 微服务应用不显示
    var allAppArr:NSMutableArray = NSMutableArray.init();//全部微应用信息，用于过滤数据
    var excludeList:Array<String>?   //视图中需要被排除的微应用appKey列表
    
    func createPlistFile() {
        //获取路径
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        filePath = path.appending("/allMicroDtaa.plist")
        let fileManager:FileManager=FileManager.default
        if !fileManager.fileExists(atPath: filePath) {
            let rootDic = NSMutableDictionary()
            rootDic.write(toFile: filePath, atomically: true)
        }else{
            var rootData:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile: filePath) ?? NSMutableDictionary.init()
            currentStoreDataArr=rootData["currentStore"] as? NSMutableArray ?? NSMutableArray.init()
        }
    }
    
    func getStoreData()  {
        createPlistFile()
    }
    
    //MARK:-file-Method
    
    //保存数据
    func savePlistData() {
        
        let rootDic = NSMutableDictionary(contentsOfFile: filePath) //根
        rootDic!.setObject(currentStoreDataArr, forKey: "currentStore" as NSCopying)
        rootDic!.write(toFile: filePath, atomically: true)
        print("保存成功")
        
        //        TinyFileManger.sharedInstance().changeData(withPath: cachePath, data: currentStoreDataArr, key:"cachePath", handleType: HandleType.add) { (success) in
        //
        //        }
        //        print("保存成功")
    }
    
    
    //MARK:-operation-methods
    
    func storeData(_ list: [Any]?) {
        guard let r_list = list else {
            return;
        }         // r_list 包含了所有微应用
        self.createPlistFile()
        currentStoreDataArr.removeAllObjects();//移除所有数据进行同步
        //存放微应用
        currentStoreDataArr.addObjects(from: r_list);//移除所有数据进行同步
        savePlistData();
    }
    
    
    //是否在存储的app中
    func isInStoreOrVersionNotChange(item:Dictionary<String,Any>) -> Bool {
        if let aimAppkey=item["appKey"] {
            let predicate:NSPredicate = NSPredicate(format: "appKey =  %@ ",aimAppkey as! CVarArg)
            if currentStoreDataArr.count>0 {
                for group in currentStoreDataArr{
                    let groupDic = group as? Dictionary<String,Any>
                    if ((groupDic?["data"]) != nil)  {
                        let d_list=groupDic!["data"] as! NSMutableArray
                        let reArray = d_list.filtered(using: predicate)
                        if reArray.count>0 {//找到在原有存储的数组里
                            //判断 版本号是不是有新的
                            if  let  resourceVersion = item["resourcesVersion"] as? String {
                                if let storeResourceV = (reArray[0] as? Dictionary<String,Any>)?["resourcesVersion"] as? String{
                                    let result = resourceVersion.compare(storeResourceV, options: .numeric)
                                    switch result {
                                    case .orderedSame : break
                                    case .orderedAscending : break
                                    case .orderedDescending : return false
                                    }
                                }
                            }
                            
                            return true
                        }
                    }
                }
            }else{
                //第一次默认初始化无红点
                return true;
            }
        }
        return false
    }
    
    //************************
    
    func checkOpenAppInStore(model:MicroAppModels)  {
        model.isNeedNewMark=false;
    }
    
    
    
    func prepareForAllAppDataJson(allApp:NSMutableArray) -> NSMutableArray {
        let finallArr:NSMutableArray=NSMutableArray.init()
        for i in 0 ..< allApp.count{
            let infoDic:NSMutableDictionary = NSMutableDictionary.init();
            
            let tempDatainfo = NSMutableDictionary.init(dictionary: (allApp[i] as? Dictionary<String, Any> ?? Dictionary<String, Any>.init()))
            infoDic.setObject(tempDatainfo["section"], forKey: "section" as NSCopying)
            let tempDataArr=NSMutableArray.init()
            for j in 0 ..< (tempDatainfo["data"] as! NSMutableArray).count {
                if let itemDic = ((tempDatainfo["data"] as? NSMutableArray)?[j] as! MicroAppModels).sourceDic{
                    tempDataArr .add(itemDic);
                }
            }
            infoDic.setObject(tempDataArr, forKey: "data" as NSCopying)
            
            finallArr.add(infoDic)
        }
        return finallArr
    }
    //修改myApp.info  增减(舍弃)
    func prepareForMyAppDataJson(isAdd:NSNumber,addDic:NSDictionary? = nil,myApps:NSMutableArray? = nil,myPath:String,myKey:String){
        if isAdd == 1{
            let formateAddDic=NSMutableDictionary.init()
            formateAddDic.setObject(addDic?["appKey"] ?? "", forKey: "appKey" as NSCopying)
            formateAddDic.setObject(addDic?["appName"] ?? "", forKey: "title" as NSCopying)
            formateAddDic.setObject(addDic?["icon"] ?? "", forKey: "thumbnailUrl" as NSCopying)
            formateAddDic.setObject(addDic?["resourcesVersion"] ?? "", forKey: "resourcesVersion" as NSCopying)
            formateAddDic.setObject(addDic?["status"] ?? "", forKey: "status" as NSCopying)
            formateAddDic.setObject(addDic?["platform"] ?? "", forKey: "platform" as NSCopying)
            TinyFileManger.sharedInstance().addInsideData(withPath:myPath, data:formateAddDic, key: myKey) { (success) in
                if success{
                    
                }
            }
            
        }else if isAdd == 0{
            let myAppArr:NSMutableArray = NSMutableArray.init()
            for  i in 0 ..< myApps!.count{
                if let aSourceDic:NSMutableDictionary = (myApps![i] as! MicroAppModels).sourceDic{
                    let formateAddDic=NSMutableDictionary.init()
                    formateAddDic.setObject(aSourceDic["appKey"] ?? "", forKey: "appKey" as NSCopying)
                    formateAddDic.setObject(aSourceDic["appName"] ?? "", forKey: "title" as NSCopying)
                    formateAddDic.setObject(aSourceDic["icon"] ?? "", forKey: "thumbnailUrl" as NSCopying)
                    formateAddDic.setObject(aSourceDic["resourcesVersion"] ?? "", forKey: "resourcesVersion" as NSCopying)
                    formateAddDic.setObject(aSourceDic["status"] ?? "", forKey: "status" as NSCopying)
                    formateAddDic.setObject(aSourceDic["platform"] ?? "", forKey: "platform" as NSCopying)
                    myAppArr.add(aSourceDic)
                }
            }
            TinyFileManger.sharedInstance().changeData(withPath: myKey, data: myAppArr, key:myKey) { (success) in
                if success{
                    
                }
            }
        }
    }
    //交换my原始数据
    func insertWith(moveItem:MicroAppModels, aimItem:MicroAppModels ,handleArr:NSMutableArray)  {
        let moveIdx = self.indexInArr(item: moveItem, handleArr: handleArr)
        let aimIdx = self.indexInArr(item: aimItem, handleArr: handleArr)
        if (moveIdx>=0)&&(aimIdx>=0){
            let moveItem = handleArr[moveIdx] as! MicroAppModels
            handleArr.removeObject(at: moveIdx)
            handleArr.insert(moveItem, at: aimIdx)
        }
    }
    
    func indexInArr(item:MicroAppModels,handleArr:NSMutableArray) -> Int {
        var idx:Int  = -1
        for i in 0..<handleArr.count {
            let model:MicroAppModels = handleArr[i] as! MicroAppModels
            if item.appKey == model.appKey {
                idx = i
                return idx
            }
        }
        return idx
    }
    func myEndEdit(myApps:NSMutableArray,allApps:NSMutableArray,dataPath:String,dataKey:String ,myPath:String,myKey:String)  {
        
        let formatAllAppData = self.prepareForAllAppDataJson(allApp: allApps)
        TinyFileManger.sharedInstance().changeData(withPath: dataPath, data: formatAllAppData, key: dataKey)
        let myAppArr:NSMutableArray = NSMutableArray.init()
        for  i in 0 ..< myApps.count{
            if let aSourceDic:NSMutableDictionary = (myApps[i] as! MicroAppModels).sourceDic{
                let formateAddDic=NSMutableDictionary.init()
                formateAddDic.setObject(aSourceDic["appKey"] ?? "", forKey: "appKey" as NSCopying)
                if aSourceDic["appName"] != nil {
                    formateAddDic.setObject(aSourceDic["appName"] ?? "", forKey: "title" as NSCopying)
                }else{
                    formateAddDic.setObject(aSourceDic["title"] ?? "", forKey: "title" as NSCopying)
                }
                if aSourceDic["thumbnailUrl"] != nil {
                    formateAddDic.setObject(aSourceDic["thumbnailUrl"] ?? "", forKey: "thumbnailUrl" as NSCopying)
                }else{
                    formateAddDic.setObject(aSourceDic["icon"] ?? "", forKey: "icon" as NSCopying)
                }
                formateAddDic.setObject(aSourceDic["resourcesVersion"] ?? "", forKey: "resourcesVersion" as NSCopying)
                formateAddDic.setObject(aSourceDic["status"] ?? "", forKey: "status" as NSCopying)
                formateAddDic.setObject(aSourceDic["platform"] ?? "", forKey: "platform" as NSCopying)
                myAppArr.add(formateAddDic)
            }
        }
        TinyFileManger.sharedInstance().changeData(withPath: myPath, data: myAppArr, key:myKey);
    }
    //获取mallApp
    func getMallAppData() {
        if mallAppArr.count <= 0 {
            mallAppArr.removeAllObjects();
            let moreAppData = TinyFileManger.sharedInstance().getDataWithPath("mallAppList.json", key: "mallAppList")
            if moreAppData is NSArray {
                let arr = moreAppData as! NSArray
                for obj in arr {
                    let  model=MicroAppModels.init()
                    let dic = obj as? Dictionary<String,Any>
                    model.configWithParam(params: dic ?? Dictionary<String,Any>.init())
                    mallAppArr.add(model)
                }
            }
        }
    }
    
    //获取allApp
    func getAllAppData() {
        allAppArr.removeAllObjects()
        if allAppArr.count <= 0 {
            let allAppData = TinyFileManger.sharedInstance().getDataWithPath("allApp.json", key: "allApp.dataInfos")
            if allAppData is NSArray {
                let ary = allAppData as! NSArray
                for obj in ary {
                    let dic = obj as! NSDictionary
                    let subAry = dic["data"]! as! NSArray
                    for app in subAry {
                        let model = MicroAppModels.init()
                        let dic = app as? Dictionary<String,Any>
                        model.configWithParam(params: dic ?? Dictionary<String,Any>.init())
                        allAppArr.add(model)
                    }
                }
            }
        }
    }
    
    //判断是不是服务微应用 下架微应用 安卓微应用 excludeList不显示微应
    func filtration(dataDic:Dictionary<String,Any>) -> Bool {
        if dataDic["appKey"] != nil {
            let appKey = "\(dataDic["appKey"]!)"
            for item in mallAppArr {
                let  model:MicroAppModels =  item as! MicroAppModels;
                if model.appKey ==  appKey{
                    if model.micAppType == "1" {
                        return true
                    }
                }
            }
            //excludeList不显示微应
            if (excludeList?.count ?? 0) > 0 {
                if excludeList!.contains(appKey){
                    return true
                }
            }
        }
        
        if dataDic["status"] != nil{
            let status = "\(dataDic["status"]!)"
            if status == "1" {//下架1
                return true
            }
        }
        
        if dataDic["platform"] != nil{
            let platform = "\(dataDic["platform"]!)"
            if platform.count>0 {
                if platform == "2" {//安卓微应用过滤
                    return true
                }
            }else{
                return compare(app: dataDic)
            }
        }else{
            return compare(app: dataDic)
        }
        
        if dataDic["isHide"] != nil{
            let isHide = "\(dataDic["isHide"]!)"
            if isHide == "1" {//隐藏
                return true
            }
        }
        
        return false;
    }
    
    public func compare(app:Dictionary<String,Any>) -> Bool{
        for item in allAppArr {
            let model = item as! MicroAppModels
            let appKey = app["appKey"]! as! String
            if appKey == model.appKey {
                if model.platform == "2"{
                    return true
                }
            }
        }
        return false
    }
    
    public class   func loadImageWithUrlPath(path: String, dependencePath:String,callBack:@escaping (_ image: UIImage) ->() ) {
        var tempPath = path.replacingOccurrences(of: "url(", with: "")
        tempPath = tempPath.replacingOccurrences(of: ")", with: "")
        var imagePath = TinyTheme.config(withType:NSNumber(1), param: tempPath)
        var remote = imagePath.contains("http") || tempPath.contains("https")
        if (!remote) {
            imagePath = TYTinyConfig.sharedInstance().fullPathBaseUrls(withPath: imagePath, apiRule: false)
            remote = imagePath.contains("http") || tempPath.contains("https")
        }
        let url: NSURL?
        if !remote{
            url = NSURL(string: imagePath, relativeTo: NSURL(fileURLWithPath:dependencePath) as URL)
        }else {
            url = NSURL(string: imagePath)
        }
        
        let request = TinyRequest.request(withURIString: (url?.absoluteString)!, relativeTo: nil) as! TinyRequest
        TinyNetworkCenter.loadImageRequest(request)
        request.completionBlock = { (response, error) in
            if error == nil {
                if let im = response as? UIImage {
                    callBack(im)
                }else{
                    callBack(UIImage(data: response as? Data ?? Data.init()) ?? UIImage.init())
                }
            }
        }
    }
    
    public func changeThemeIconForCell(dataSource:Dictionary<String,Any>){
        let myArr:Array = (dataSource["my"] as! Array<Any>)
        for item in myArr {
            let model=item as! MicroAppModels
            let themeIcon:String = TinyTheme.config(withType: 1, param: String(format: "?theme/%@", model.appKey as! CVarArg))
            if themeIcon !=  String(format: "?theme/%@", model.appKey as! CVarArg){
                model.icon=themeIcon;
            }
        }
        
        let groupAllArr:Array = (dataSource["group"] as! Array<Any>)
        
        for groupParam in groupAllArr {
            let  groupDic:Dictionary<String,Any>  = groupParam as! Dictionary<String,Any>
            let agroupArr=groupDic["data"] as! Array<Any>
            for item in agroupArr {
                let model=item as! MicroAppModels
                let themeIcon:String = TinyTheme.config(withType: 1, param: String(format: "?theme/%@", model.appKey as! CVarArg))
                if themeIcon !=  String(format: "?theme/%@", model.appKey as! CVarArg){
                    model.icon=themeIcon;
                }
            }
        }
    }
}
